package com.stephen.redisdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.stephen.redisdemo.dao.UserMapper;
import com.stephen.redisdemo.entity.User;
import com.stephen.redisdemo.entity.enums.ResultEnum;
import com.stephen.redisdemo.entity.vo.CommonResponse;
import com.stephen.redisdemo.entity.vo.PageParam;
import com.stephen.redisdemo.entity.vo.PageResult;
import com.stephen.redisdemo.exception.BusinessException;
import com.stephen.redisdemo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final RedisTemplate redisTemplate;

    private static final String KEY = "list";

    public Object list(PageParam param) {
        if (param.getPageIndex() <= 0 || param.getPageSize() <= 0) {
            throw new BusinessException(ResultEnum.PARAM_ERROR);
        }

        Page<User> page = new Page<>(param.getPageIndex(), param.getPageSize());

        Object obj = redisTemplate.opsForValue().get(KEY);
        if (null != obj) {
            return obj;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","abc");

        IPage<User> iPage = userMapper.selectPage(page, wrapper);
        List<User> records = iPage.getRecords();
        System.out.println("records: " + records);

        PageResult<List<User>> pageResult = new PageResult<>(param.getPageIndex(), param.getPageSize(), iPage.getPages(), iPage.getTotal(), iPage.getRecords());

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.serializeNulls();
        Gson gson = gsonBuilder.create();

        redisTemplate.opsForValue().set(KEY, gson.toJson(pageResult), 1, TimeUnit.MINUTES);

        // try {
        //     int i = 1 / 0;
        // } catch (Exception e) {
        //     throw new BusinessException(1000,"这是一个自定义错误",10000);
        // }
        return CommonResponse.ok(pageResult);
    }

}
